package com.yulongtian.offers.day202209.day20220922;

import java.util.HashMap;

/**
 * https://leetcode.cn/problems/zui-chang-bu-han-zhong-fu-zi-fu-de-zi-zi-fu-chuan-lcof/
 *
 * @author YulongTian
 * @date 2022/9/22 - 10:55
 */
public class Test02 {
    public static void main(String[] args) {
        System.out.println(lengthOfLongestSubstring("aab"));
    }

    /**
     * 滑动窗口方法
     *
     * @return: int
     */
    public static int lengthOfLongestSubstring(String s) {
        if(s.length()==0){
            return 0;
        }
        int window_len = 1;//当前窗口大小
        int max_window_len = 1;//最大窗口大小
        int max_char_len = 1;//窗口中最大重复字符大小
        HashMap<Character, Integer> map = new HashMap<>();
        map.put(s.charAt(0), 1);
        for (int i = 1; i < s.length(); i++) {
            //窗口增加
            if (map.get(s.charAt(i)) == null) {
                map.put(s.charAt(i), 1);
                window_len++;
            } else {
                int tempLen = map.get(s.charAt(i));
                map.put(s.charAt(i), tempLen + 1);
                window_len++;
                max_char_len = Math.max(max_char_len, tempLen + 1);
            }
            //无重复
            if (max_char_len <= 1) {
                continue;
            }
            //有重复 从重复开始  重新加入哈希表
            window_len--;
            max_window_len=Math.max(max_window_len,window_len);
            map.clear();
            map.put(s.charAt(i-window_len+1), 1);
            i=i-window_len+1;
            max_char_len=1;
            window_len=1;
        }
        max_window_len=Math.max(max_window_len,window_len);


        return max_window_len;
    }


}
